﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Engine.Sgml {
    [DebuggerDisplay("{Count}")]
    internal class ObjectPool<T> {
        private ConcurrentBag<T> objects;
        private Func<T> constructor;

        public ObjectPool(Func<T> constructor) {
            Guard.ArgumentNotNull(constructor, "constructor");
            this.constructor = constructor;
            this.objects = new ConcurrentBag<T>();
            }

        public int Count {
            get { return objects.Count; }
            }

        public T Get() {
            T item;
            if (objects.TryTake(out item))
                return item;
            else
                return constructor();
            }

        public void Put(T item) {
            objects.Add(item);
            }
        }
    }
